//
//  YHOptionTitleImageListTableViewCell.m
//  ScriptKill
//
//  Created by 林宁宁 on 2021/4/28.
//  Copyright © 2021 优智汇. All rights reserved.
//

#import "YHOptionTitleImageListTableViewCell.h"
#import "YHOptionTableViewItemImageList.h"
#import "YHPhotoManager.h"
#import "YHImageScanTool.h"
#import "YHBaseCollectionViewCell.h"
#import "UIButton+YH.h"
#import "YHHUD.h"
#import "UIImageView+YHWebImage.h"
#import "UIScrollView+YHNoData.h"
#import "UIImage+YH.h"


@interface YHOptionTitleImageListCollectionCell : YHBaseCollectionViewCell

@property (retain, nonatomic) UIImageView * cellImageView;
@property (retain, nonatomic) UIButton * cellCloseBtn;

@property (retain, nonatomic) YHOptionTableViewImageItem * cellItem;

@property (copy, nonatomic) void(^deleteBlock)(YHOptionTableViewImageItem * passItem,NSIndexPath * indexPath);

@end

@implementation YHOptionTitleImageListCollectionCell

-(void)yh_commonInit{
    self.cellImageView = [UIImageView new];
    self.cellImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.contentView addSubview:self.cellImageView];
    [self.cellImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(5, 0, 5, 10));
    }];
    
    WS(weakSelf)
    self.cellCloseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.cellCloseBtn setImage:[UIImage imageNamed:@"close_mini"] forState:UIControlStateNormal];
    [self.cellCloseBtn addActionHandler:^(UIButton *sender, NSInteger tag) {
        if(weakSelf.deleteBlock){
            weakSelf.deleteBlock(weakSelf.cellItem,weakSelf.indexPath);
        }
    }];
    [self.contentView addSubview:self.cellCloseBtn];
    [self.cellCloseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.cellImageView.mas_right);
        make.centerY.equalTo(self.cellImageView.mas_top);
    }];
    self.cellCloseBtn.hidden = YES;
}

-(void)setCellItem:(YHOptionTableViewImageItem *)cellItem{
    _cellItem = cellItem;
    
    id obj = cellItem.image;
    if([obj isKindOfClass:[NSString class]]){
        [self.cellImageView yh_setImage:obj];
    }
    else if([obj isKindOfClass:[UIImage class]]){
        UIImage * image = (UIImage *)obj;
        self.cellImageView.image = image;
    }
}

@end



@interface YHOptionTitleImageListTableViewCell()<UICollectionViewDelegate, UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (retain, nonatomic) UICollectionView * collectionView;

@end

@implementation YHOptionTitleImageListTableViewCell

-(void)yh_optionInit{
    
    UICollectionViewFlowLayout * flowLayout = [UICollectionViewFlowLayout new];
    flowLayout.minimumLineSpacing = self.isFullCell?15:0;
    flowLayout.minimumInteritemSpacing = flowLayout.minimumLineSpacing;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.sectionInset = UIEdgeInsetsZero;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:self.collectionView];
    
    [self.collectionView emptyConfig:^(YHDZNEmptyDelegate * _Nonnull delegate) {
        delegate.title = @"";
        delegate.imageUrlString = nil;
    }];
    
    [self.collectionView registerClass:YHOptionTitleImageListCollectionCell.class forCellWithReuseIdentifier:YHOptionTitleImageListCollectionCell.cellIndentify];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.cellOptionContentView);
    }];
}

-(void)layoutSubviews{
    [super layoutSubviews];
    
    [self.collectionView reloadData];
}

-(void)setImageList:(NSMutableArray<YHOptionTableViewImageItem *> *)imageList{
    _imageList = [NSMutableArray arrayWithArray:imageList];
    
    [self.collectionView reloadData];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if(section == 0){
        return self.imageList.count;
    }
    if(self.isEdit){
        return 1;
    }
    return 0;
}

-(__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YHOptionTitleImageListCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:YHOptionTitleImageListCollectionCell.cellIndentify forIndexPath:indexPath];
    
    WS(weakSelf)
    if(indexPath.section == 0){
        YHOptionTableViewImageItem * item = self.imageList[indexPath.row];
        cell.cellItem = item;
        
        cell.cellCloseBtn.hidden = !self.isEdit;
        [cell setDeleteBlock:^(YHOptionTableViewImageItem *passItem, NSIndexPath *indexPath) {
            NSInteger index = [weakSelf.imageList indexOfObject:passItem];
            [weakSelf.imageList removeObject:passItem];
            [weakSelf.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]];
            if(weakSelf.deleteImageAction){
                weakSelf.deleteImageAction(passItem);
            }
        }];
    }else{
        cell.cellCloseBtn.hidden = YES;
        cell.cellImageView.image = [UIImage imageNamed:@"image_add"];
    }
    
    if(self.isFullCell){
        cell.cellImageView.layer.cornerRadius = 5;
        cell.cellImageView.layer.masksToBounds = YES;
    }else{
        cell.cellImageView.layer.cornerRadius = 0;
        cell.cellImageView.layer.masksToBounds = YES;
    }
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        YHOptionTableViewImageItem * item = self.imageList[indexPath.row];
        [YHImageScanTool scanImage:item.image imageURL:item.image];
    }
    else if(indexPath.section == 1){
        //添加图片
        [self endEditing:YES];
        if(self.imageList.count >= self.maxImageCount){
            YHHUDMsg([NSString stringWithFormat:@"最多%ld张图片",self.maxImageCount]);
            return;
        }
        NSInteger maxCount = MAX(0, self.maxImageCount-self.imageList.count);
        WS(weakSelf)
        YHPhotoManager * photoManager = [YHPhotoManager new];
        photoManager.manager.configuration.maxNum = maxCount;
        photoManager.manager.configuration.photoMaxNum = maxCount;
        [photoManager showSelectPhotoAndCamera:^(NSArray<HXPhotoModel *> * _Nonnull photoList, YHPhotoManager * _Nonnull manager) {
            
            YHHUDShow();
            
            dispatch_group_t group = dispatch_group_create();
            
            for(HXPhotoModel * photoModel in photoList){
                dispatch_group_enter(group);
                [photoModel getImageWithSuccess:^(UIImage * _Nullable image, HXPhotoModel * _Nullable model, NSDictionary * _Nullable info) {
                    image = [image yh_compressionLength:300*1024];
                    
                    YHOptionTableViewImageItem * passItem = [YHOptionTableViewImageItem new];
                    passItem.image = image;
                    passItem.imageType = YHOptionTableViewImageOption_Add;
                    
                    [weakSelf.imageList addObject:passItem];
                    [weakSelf.collectionView reloadData];
                    
                    if(weakSelf.addImageAction){
                        weakSelf.addImageAction(passItem);
                    }
                    dispatch_group_leave(group);
                } failed:^(NSDictionary * _Nullable info, HXPhotoModel * _Nullable model) {
                    dispatch_group_leave(group);
                }];
            }
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{
                YHHUDDismiss();
            });
        }];
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = CGRectGetHeight(collectionView.frame)*0.8;
    CGFloat width = height;
    if(self.isFullCell){
        height = CGRectGetHeight(collectionView.frame)*0.9;
        width = height*0.9;
    }
    return CGSizeMake(width, height);
}

@end
